﻿using ASmile.Extend;
using ASmile.Object;
using System;
using System.Collections.Generic;
using System.Text;

namespace ASmile
{
    public class ComActionArgs
    {
        public int Type { set; get; }

        public object Tag { set; get; }

        public DictExtend Data { set; get; }

        public Func<object, ApiResult> OnExecuteAfter { set; get; }
    }

    public interface IComAction
    {
        ApiResult Execute(ComActionArgs arg);
    }

    public class ComActionDef : IComAction
    {
        public ApiResult Execute(ComActionArgs arg)
        {
            return ApiResult.RetOK("默认未执行");
        }
    }

    public abstract class ComActionBase : IComAction
    {
        public abstract ApiResult Execute(ComActionArgs arg);

        protected ApiResult RetOK(DictExtend data)
        {
            var ret = ApiResult.RetOK();
            ret.SetExtendObj(data);
            return ret;
        }

        protected ApiResult RetOK(Action<DictExtend> OnSetData)
        {
            var data = new DictExtend();
            OnSetData?.Invoke(data);
            return RetOK(data);
        }
    }
    /// <summary>
    /// 公共执行工具类
    /// </summary>
    public static class ComActionTool
    {
        public static ApiResult Execute(string objName, ComActionArgs arg)
        {
            if (objName.IsEmpty())
            {
                return ApiResult.RetErr("执行对象名称为空");
            }
            var b = ObjectTool.GetObject<IComAction>(objName);
            if (b == null)
            {
                return ApiResult.RetErr($"执行对象({objName})不存在");
            }
            return b.Execute(arg);
        }

        public static ApiResult Execute(string objName, int type, DictExtend data)
        {
            ComActionArgs arg = new ComActionArgs();
            arg.Data = new DictExtend();
            arg.Data.SetObject(data);
            arg.Type = type;
            return Execute(objName, arg);
        }

        public static ApiResult Execute(string objName, int type, Action<DictExtend> OnSetData)
        {
            var data = new DictExtend();
            OnSetData?.Invoke(data);
            return Execute(objName, type, data);
        }

        public static ApiResult Execute(string objName, DictExtend data)
        {
            return Execute(objName, 0, data);
        }

        public static ApiResult Execute(string objName, Action<DictExtend> OnSetData)
        {
            return Execute(objName, 0, OnSetData);
        }
    }
}
